<template>
  <div>
    <!-- 顶部的导航栏 -->
    <!-- $router ---- 全局的路由对象
    $route ---- 当前页面的路由信息-->
    <van-sticky>
      <van-nav-bar left-arrow title="黑马优购" @click-left="$router.go(-1)" />
    </van-sticky>

    <!-- 列表区域 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
        <van-card
          v-for="item in goodsList"
          :key="item.goods_id"
          :num="item.goods_number"
          :price="item.goods_price"
          :title="item.goods_name"
          :thumb="item.goods_small_logo"
          @click="$router.push(`/pages/goods_detail/${ item.goods_id }`)"
        />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
export default {
  data() {
    return {
      query: "",
      cid: "",
      pagenum: 1,
      pagesize: 20,
      goodsList: [],
      total: 0,
      loading: false,
      finished: false,
      refreshing: false
    };
  },
  created() {
    // 初始化data上的数据
    this.cid = this.$route.query.cid || "";
    this.query = this.$route.query.query || "";
  },
  methods: {
    async getGoodsList() {
      this.loading = true;
      const { data: res } = await this.$http.get("/goods/search", {
        params: {
          query: this.query,
          cid: this.cid,
          pagenum: this.pagenum,
          pagesize: this.pagesize
        }
      });
      if (res.meta.status !== 200) {
        return this.$toast.fail("数据获取失败");
      }
      if (res.message.total == 0) {
        this.finished = false;
      }
      this.loading = false;
      this.refreshing = false;
      // 因为该函数会被反复触发
      // 一旦组件监听到触底了 就会自动调用该函数获取下一页的数据 所以我们要把新的数据与之前的数据进行拼接
      this.goodsList = [...this.goodsList, ...res.message.goods];
      this.total = res.message.total;
    },
    // 加载数据
    onLoad() {
      // 判断 如果没有数据
      if (this.finished) {
        return;
      }
      // 判断是否为第一次加载
      if (this.total == 0) {
        this.getGoodsList();
        return;
      }
      // 判断 数据是否加载完毕
      if (this.goodsList.length >= this.total) {
        this.finished = true;
        return;
      }
      // 加载更多
      this.pagenum++;
      this.getGoodsList();
    },
    // 下拉刷新函数
    onRefresh() {
      // 把所有的数据还原到初始状态
      this.goodsList = [];
      this.loading = false;
      this.finished = false;
      this.pagenum = 0;
      this.getGoodsList();
    }
  }
};
</script>

<style lang="less" scoped>
</style>